
package com.leave.service.Impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leave.dao.UserMapper;
import com.leave.dao.UserRoleMapper;
import com.leave.entity.Leave;
import com.leave.entity.User;
import com.leave.entity.UserRole;
import com.leave.service.IUserService;

@Service
public class UserServiceImpl implements IUserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	/**
	 * 根据用户名获取用户实例
	 */
	public User getUserByLoginName(String loginName) {
		User u = userMapper.getUserByLoginName(loginName);
		
		
		return u;
	}

	
	public HashMap<String,Object> getAllUserByPage(Integer page, Integer rows) {
		PageHelper.startPage(page,rows);
		List<User> userList = userMapper.getAllUserByPage();
		PageInfo<User> pageInfo = new PageInfo<User>(userList);
		Long total = pageInfo.getTotal();
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("userList", userList);
		map.put("total", total);
		return map;
	}


	public int removeUserByArrId(int[] arrId) {
		int i = userMapper.deleteUserByArrId(arrId);
		
		return i;
	}


	public int addUser(User u) {
		int i = userMapper.insertSelective(u);
		return i;
	}


	public int updateUserByUser(User u) {
		int i = userMapper.updateByPrimaryKeySelective(u);
		return i;
	}


	public HashMap<String, Object> getAllUserAndHasRoleByPage(Integer page, Integer rows) {
		PageHelper.startPage(page,rows);
		List<User> userList = userMapper.getAllUserAndHasRoleByPage();
		PageInfo<User> pageInfo = new PageInfo<User>(userList);
		Long total = pageInfo.getTotal();
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("userList", userList);
		map.put("total", total);
		return map;
	}

	/**
	 * 删除用户所有的角色
	 */
	public int deleteRoleOfUser(int userId) {
		return userMapper.deletRoleOfUser(userId);
	}
	
	/**
	 * 新增
	 */
	public int addRoleOfUser(int userId,int[] roleId) {
		List<UserRole> userRoleList = new ArrayList<UserRole>();
		for(int i = 0 ;i < roleId.length;i++) {
			UserRole userRole = new UserRole();
			userRole.setUserId(userId);
			userRole.setRoleId(roleId[i]);
			userRoleList.add(userRole);
		}
		
		return userRoleMapper.addRoleOfUser(userRoleList);
	}

	/**
	 * 根据角色名获取其下的所有用户
	 */
	public List<User> getUserListByRole(String roleName) {
		List<User> userList = userMapper.getUserListByRole(roleName);
		return userList;
	}


	public User getUserNameByLeave(Leave leave) {
		
		return userMapper.getUserByLeave(leave.getLeaveId());
	}


	public User getUserById(String userId) {
		Integer id = Integer.valueOf(userId);
		return userMapper.selectByPrimaryKey(id);
	}
	
}
